﻿using AutoMapper;
using BS.Infra;
using BS.Infra.Interface;
using MediatR;

namespace BS.Write.Api.Handler.RBAC
{
    public class DelUserFromRoleCommandHandler : IRequestHandler<RemoveUserFromRoleCommand, ApiResult>
    {
        private readonly ILogger<DelUserFromRoleCommandHandler> _logger;

        private readonly IUserRepository _userRepository;

        private readonly IRoleRepository _roleRepository;

        private readonly IMapper _mapper;
        public DelUserFromRoleCommandHandler(ILogger<DelUserFromRoleCommandHandler> logger, IUserRepository userRepository, IRoleRepository roleRepository, IMapper mapper)
        {
            _logger = logger;
            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(RemoveUserFromRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var user = await _userRepository.GetAsync(x=>x.UserId==request.UserId);
                if (user.UserId == null)
                {
                    return  ApiResult.Fail("用户不存在");
                }
                user.IsDeleted = true;
                await _userRepository.UpdateAsync(user);
                return  ApiResult.Ok("删除成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除用户角色失败");
                return  ApiResult.Fail("删除失败");
            }
        }
    }
}
public class RemoveUserFromRoleCommand:IRequest<ApiResult>
{
    public int UserId { get; set; }
}